<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8" />
    <title>订单管理 - 订餐管理系统</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" />
    <link rel="stylesheet" href="dish-management.css" />
    <link rel="stylesheet" href="通用新页面css.css" />
    <link rel="stylesheet" href="popNotification.css" />
    <style>
        .order-detail {
            padding: 20px;
        }
        .detail-header {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }
        .dish-list {
            margin-top: 20px;
        }
        .dish-item {
            display: flex;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .dish-item img {
            width: 60px;
            height: 45px;
            object-fit: cover;
            margin-right: 15px;
            border-radius: 4px;
        }
        .dish-info {
            flex: 1;
        }
        .dish-name {
            font-weight: 500;
        }
        .dish-description {
            font-size: 0.8rem;
            color: #666;
            margin-top: 4px;
        }
        .dish-amount {
            font-weight: 600;
        }
        .total-amount {
            text-align: right;
            margin-top: 20px;
            font-size: 18px;
            font-weight: 600;
            color: #dc3545;
        }
        .no-image {
            width: 60px;
            height: 45px;
            background-color: #f5f5f5;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 15px;
            border-radius: 4px;
            font-size: 0.8rem;
            color: #999;
        }
        /* 加载状态样式 */
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        /* 表格内容换行样式 */
        td {
            white-space: normal;
            word-wrap: break-word;
            max-width: 200px;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
        }
        .status-cancelled {
            background-color: #f8d7da;
            color: #721c24;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
        }
        .status-completed {
            background-color: #e6f7e6;
            color: #28a745;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8rem;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="container">
        <div class="sidebar">
            <a href="mainpage.html" class="sidebar-item">首页</a>
            <a href="dish-management.html" class="sidebar-item">菜品管理</a>
            <a href="order-management.html" class="sidebar-item active">订单管理</a>
            <a href="marketing-statistics.html" class="sidebar-item">营销统计</a>
            <a href="UserPage.html" class="sidebar-item">用户管理</a>
        </div>
        <!-- 主内容区 -->
        <div class="content">
            <div class="header">
                <h1>订单管理</h1>
            </div>
            <!-- 搜索区域（仅保留订单编号搜索） -->
            <div class="search-area">
                <input
                        type="text"
                        v-model="searchOrderNo"
                        placeholder="请输入订单编号" />
                <button @click="search">查询</button>
                <button class="reset" @click="reset">重置</button>
            </div>
            <!-- 订单列表表格 -->
            <table>
                <thead>
                <tr>
                    <th>订单编号</th>
                    <th>用户名称</th>
                    <th>手机号</th>
                    <th>收货地址</th>
                    <th>订单金额</th>
                    <th>支付状态</th>
                    <th>订单状态</th>
                    <th>备注</th>
                    <th>下单时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="order in orders" :key="order.id">
                    <td>{{ order.orderNumber }}</td>
                    <td>{{ order.buyer }}</td>
                    <td>{{ order.phone }}</td>
                    <td>{{ order.address || '无' }}</td>
                    <td>¥{{ order.totalAmount.toFixed(2) }}</td>
                    <td>{{ order.payState === 1 ? '已支付' : '未支付' }}</td>
                    <td>
                        <span :class="order.orderState === 0 ? 'status-pending' :
                                   order.orderState === 1 ? 'status-cancelled' : 'status-completed'">
                            {{ order.orderState === 0 ? '新单' :
                               order.orderState === 1 ? '取消' : '完成' }}
                        </span>
                    </td>
                    <td>{{ order.notes || '无' }}</td>
                    <td>{{ formatDateTime(order.createTime) }}</td>
                    <td class="operation">
                        <button class="edit" @click="viewOrder(order.id)">查看</button>
                    </td>
                </tr>
                <tr v-if="orders.length === 0">
                    <td colspan="10" style="text-align: center; padding: 20px;">暂无订单数据</td>
                </tr>
                </tbody>
            </table>
            <!-- 分页控件 -->
            <div class="pagination">
                <select v-model="pageSize" @change="search">
                    <option value="5">5条/页</option>
                    <option value="10">10条/页</option>
                    <option value="15">15条/页</option>
                </select>
                <button @click="prevPage" :disabled="currentPage === 1">
                    上一页
                </button>
                <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
                <button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
                前往
                <input type="number" v-model.number="jumpPage" min="1" :max="totalPages" />
                页
                <button @click="goToPage">跳转</button>
            </div>
        </div>
    </div>

    <!-- 订单详情弹窗 -->
    <div class="popNotification" v-if="showDetail">
        <div class="form-card">
            <div class="form-header">
                <h1 class="form-title"><i class="fa fa-list-alt"></i>订单详情</h1>
            </div>

            <!-- 加载状态 -->
            <div v-if="isLoading" class="loading">
                <i class="fa fa-spinner fa-spin"></i> 加载中...
            </div>

            <!-- 详情内容 -->
            <div class="order-detail" v-else>
                <div class="detail-header">
                    <p><strong>订单编号：</strong>{{ currentOrder.orderNumber }}</p>
                    <p><strong>用户名称：</strong>{{ currentOrder.buyer }}</p>
                    <p><strong>联系电话：</strong>{{ currentOrder.phone }}</p>
                    <p><strong>收货地址：</strong>{{ currentOrder.address || '无' }}</p>
                    <p><strong>备注信息：</strong>{{ currentOrder.notes || '无' }}</p>
                    <p><strong>下单时间：</strong>{{ formatDateTime(currentOrder.createTime) }}</p>
                    <p><strong>订单状态：</strong>
                        <span :class="currentOrder.orderState === 0 ? 'status-pending' :
                                   currentOrder.orderState === 1 ? 'status-cancelled' : 'status-completed'">
                            {{ currentOrder.orderState === 0 ? '新单' :
                               currentOrder.orderState === 1 ? '取消' : '完成' }}
                        </span>
                    </p>
                </div>

                <h3>菜品列表</h3>
                <div class="dish-list">
                    <!-- 循环展示所有订购的菜品 -->
                    <div class="dish-item" v-for="(item, index) in currentOrder.dishItems" :key="index">
                        <!-- 处理图片显示，支持base64和URL -->
                        <template v-if="item.image">
                            <img :src="item.image" :alt="item.dishName || '菜品图片'">
                        </template>
                        <template v-else>
                            <span class="no-image">无图片</span>
                        </template>

                        <div class="dish-info">
                            <div class="dish-name">{{ item.dishName || '未知菜品' }}</div>
                            <div>单价：¥{{ item.price ? item.price.toFixed(2) : '0.00' }} × {{ item.quantity || 0 }}</div>
                            <!-- 显示菜品描述（如果有） -->
                            <div class="dish-description" v-if="item.description">
                                {{ item.description }}
                            </div>
                        </div>

                        <div class="dish-amount">
                            ¥{{ item.subtotal ? item.subtotal.toFixed(2) : '0.00' }}
                        </div>
                    </div>

                    <!-- 处理没有菜品的情况 -->
                    <div v-if="!currentOrder.dishItems || currentOrder.dishItems.length === 0" style="text-align: center; padding: 20px;">
                        暂无菜品信息
                    </div>
                </div>

                <div class="total-amount">
                    订单总金额：¥{{ currentOrder.totalAmount ? currentOrder.totalAmount.toFixed(2) : '0.00' }}
                </div>
            </div>
            <div class="form-actions">
                <button class="btn btn-cancel" @click="showDetail = false">关闭</button>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    const { createApp, reactive, ref, onMounted } = Vue;
    createApp({
        setup() {
            // 订单数据
            const orders = ref([]);
            const totalPages = ref(0);
            const totalOrders = ref(0);

            // 查询参数（仅保留订单编号搜索）
            const searchOrderNo = ref("");

            // 分页参数
            const currentPage = ref(1);
            const pageSize = ref(5);
            const jumpPage = ref(1);

            // 详情弹窗相关
            const showDetail = ref(false);
            const currentOrder = ref({
                dishItems: [] // 初始化dishItems为数组
            });
            const isLoading = ref(false); // 加载状态

            // 页面加载时自动请求数据
            onMounted(() => {
                fetchOrders();
            });

            // 格式化日期时间
            const formatDateTime = (dateTime) => {
                if (!dateTime) return '';
                return dateTime.replace('T', ' ');
            };

            // 获取订单列表
            const fetchOrders = async () => {
                try {
                    const params = {
                        pageNum: currentPage.value,
                        pageSize: pageSize.value,
                        torder: {
                            orderNumber: searchOrderNo.value
                        }
                    };

                    const response = await axios.post(
                        "/t-order/listPage",
                        params,
                        {
                            headers: {
                                "Content-Type": "application/json",
                                Authorization: "Bearer " + localStorage.getItem("food_token")
                            }
                        }
                    );

                    console.log("订单数据:", response.data.data)
                    if (Array.isArray(response.data.data)) {
                        orders.value = response.data.data.map(order => ({
                            ...order,
                            dishItems: order.dishItems || []
                        }));
                        totalOrders.value = response.data.total;
                        totalPages.value = Math.ceil(totalOrders.value / pageSize.value);
                        jumpPage.value = currentPage.value;
                    } else {
                        alert("获取订单失败：" + (response.data.msg || "未知错误"));
                    }
                } catch (error) {
                    console.error("订单查询失败：", error);
                    alert("订单查询失败，请重试");
                }
            };

            // 搜索方法
            const search = () => {
                currentPage.value = 1;
                fetchOrders();
            };

            // 重置搜索
            const reset = () => {
                searchOrderNo.value = "";
                search();
            };

            // 分页方法
            const prevPage = () => {
                if (currentPage.value > 1) {
                    currentPage.value--;
                    fetchOrders();
                }
            };

            const nextPage = () => {
                if (currentPage.value < totalPages.value) {
                    currentPage.value++;
                    fetchOrders();
                }
            };

            const goToPage = () => {
                if (jumpPage.value >= 1 && jumpPage.value <= totalPages.value) {
                    currentPage.value = jumpPage.value;
                    fetchOrders();
                } else {
                    alert(`请输入1-${totalPages.value}之间的页码`);
                }
            };

            // 查看订单详情 - 通过请求体传递id参数
            const viewOrder = async (id) => {
                try {
                    // 显示加载状态
                    isLoading.value = true;
                    showDetail.value = true;

                    // 构造请求数据对象
                    const requestData = {
                        id: id
                    };

                    // 发送POST请求，通过请求体传递订单ID
                    const response = await axios.post(
                        "/t-order/order_detail",
                        requestData,
                        {
                            headers: {
                                "Content-Type": "application/json",
                                Authorization: "Bearer " + localStorage.getItem("food_token")
                            }
                        }
                    );

                    console.log("订单详情数据:", response.data.data);

                    if (response.data.data) {
                        // 确保dishItems存在且为数组
                        currentOrder.value = {
                            ...response.data.data,
                            dishItems: response.data.data.dishItems || []
                        };
                    } else {
                        alert("获取订单详情失败：未找到订单数据");
                    }
                } catch (error) {
                    console.error("获取订单详情失败：", error);
                    alert("获取订单详情失败，请重试");
                } finally {
                    // 隐藏加载状态
                    isLoading.value = false;
                }
            };

            return {
                orders,
                totalPages,
                currentPage,
                pageSize,
                jumpPage,
                searchOrderNo,
                showDetail,
                currentOrder,
                isLoading,
                formatDateTime,
                search,
                reset,
                prevPage,
                nextPage,
                goToPage,
                viewOrder
            };
        }
    }).mount("#app");
</script>
</html>
